package com.earthea.scaffold.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.earthea.cache.CacheService;
import com.earthea.common.util.JacksonUtils;
import com.earthea.scaffold.common.constant.Constants;
import com.earthea.scaffold.common.entity.BaseCollectionRsp;
import com.earthea.scaffold.common.enums.CacheEnum;
import com.earthea.scaffold.common.service.BaseService;
import com.earthea.scaffold.domain.DictData;
import com.earthea.scaffold.domain.DictType;
import com.earthea.scaffold.mapper.DictDataMapper;
import com.earthea.scaffold.mapper.DictTypeMapper;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 */
@Service
public class DictTypeService extends BaseService<DictType, DictTypeMapper> {
    @Autowired
    private DictDataMapper dictDataMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    /**
     * 查询所有字典类型
     *
     * @return 字典类型集合信息
     */
    public BaseCollectionRsp<DictType> selectAll() {
        return new BaseCollectionRsp<>(mapper.selectList(new QueryWrapper<>()));
    }

    /**
     * 重置字典缓存数据
     */
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 加载字典缓存数据
     */
    private void loadingDictCache() {
        DictData dictData = new DictData();
        Map<String, List<DictData>> dictDataMap = dictDataMapper.selectList(dictData).stream().collect(Collectors.groupingBy(DictData::getDictType));
        for (Map.Entry<String, List<DictData>> entry : dictDataMap.entrySet()) {
            cacheService.setex(getCacheKey(entry.getKey()), JacksonUtils.toJson(entry.getValue().stream().sorted(Comparator.comparing(DictData::getDictDataId)).collect(Collectors.toList())), Constants.DEFAULT_CACHE_TIMEOUT);
        }
    }

    /**
     * 清空字典缓存数据
     */
    private void clearDictCache() {
        Collection<String> keys = cacheService.keys(CacheEnum.SYS_DICT.getAllCacheKey());
        for (String key : keys) {
            cacheService.del(key);
        }
    }

    private String getCacheKey(String configKey) {
        return CacheEnum.SYS_DICT.getCacheKey(configKey);
    }
}